﻿using Codemonk.Common.Emit;
using System;
using System.Reflection;

namespace Codemonk.Common.Aspect
{
    /// <summary>
    /// 运行时方法
    /// 仅仅能包含对象的公开，实例方法
    /// </summary>
    public sealed class InterceptedMethod
    {
        private static TypeAccessorFactory factory = new TypeAccessorFactory();

        private readonly Type callType;

        private readonly string methodName;

        public InterceptedMethod(object caller, MethodInfo method, object[] parameters)
        {
            if (caller == null || method == null) throw new NullReferenceException();
            callType = caller.GetType();
            methodName = method.Name;
            this.Caller = caller;
            this.MethodInfo = method;
            this.Paramaters = parameters;
        }

        /// <summary>
        /// 当前方法的调用者
        /// </summary>
        public object Caller { get; private set; }
        /// <summary>
        /// 运行时方法
        /// </summary>
        public MethodInfo MethodInfo { get; private set; }
        /// <summary>
        /// 运行时参数
        /// </summary>
        public object[] Paramaters { get; private set; }

        public object Invoke()
        {
            return factory.GetByType(callType).ExecuteFunc(Caller, methodName, Paramaters);
        }
    }
}
